import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_module_appaat/common/api/result_data.dart';
import 'package:flutter_module_appaat/common/utils/log_util.dart';

/// common api
import 'api.dart';
import 'code.dart';
import 'common_result.dart';

///
/// <pre>
///     author : Wp
///     e-mail : 神舟友创
///     time   : 2019/7/7 8:35 PM
///     desc   : 网络请求工具类
///     version: 1.0
/// </pre>
///

var dio = new Dio();

class NetUtils {
  static void init(HttpOptionsModel options) {
    dio.options.baseUrl = options.baseUrl;
    dio.options.connectTimeout = options.connectTimeout;
    dio.options.receiveTimeout = options.receiveTimeout;
    dio.options.headers = options.headers;
//    dio.options.contentType =
//        ContentType.parse("application/x-www-form-urlencoded");
  }

//  static Future get(
//      String url, Map<String, dynamic> params, CancelToken cancelToken) async {
//    var response;
//
//    if (params != null) {
//      response = await dio.get(Api.BASE_URL + url,
//          queryParameters: params, cancelToken: cancelToken);
//    } else {
//      response = await dio.get(Api.BASE_URL + url);
//    }
//    return response.data;
//  }

  static Future<ResultData> get(String url, {CancelToken cancelToken}) async {
    print(
        "\n--------------------------------------------请求start--------------------------------------------\n\n");
    print("请求url：${Api.BASE_URL + url}\n");
    Response response;
    try {
      if (null == cancelToken) {
        cancelToken = CancelToken();
      }
      response = await dio.get(Api.BASE_URL + url, cancelToken: cancelToken);
    } on DioError catch (e) {
      Response errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT || e.type == DioErrorType.RECEIVE_TIMEOUT) {
        errorResponse.statusCode = -2; //NETWORK_TIMEOUT
      }
      print("抛出异常：${e.message}\n");
      print(
          "\n--------------------------------------------请求end--------------------------------------------\n\n");
      return new ResultData(Code.errorHandleFunction(errorResponse.statusCode, e.message), false,
          errorResponse.statusCode, 0);
    }
    LogUtil.e("请求结果：$response\n");
    print(
        "\n--------------------------------------------请求end--------------------------------------------\n\n");
    // 过滤器
    CommonResult result = new CommonResult.fromJson(response.data);
    //1成功,0失败
    if (result.code == 1) {
      return new ResultData(result.data, true, result.code, result.total, message: result.message);
    } else {
      return new ResultData(result.data, false, result.code, result.total, message: result.message);
    }
  }

  static Future<ResultData> post(String url, Map<String, dynamic> params,
      {CancelToken cancelToken}) async {
    print(
        "\n--------------------------------------------请求start--------------------------------------------\n\n");
    print("请求url：${Api.BASE_URL + url}\n");
    print("请求参数：$params\n");
    Response response;
    try {
      if (null == cancelToken) {
        cancelToken = CancelToken();
      }
      response = await dio.post(Api.BASE_URL + url, data: params, cancelToken: cancelToken);
    } on DioError catch (e) {
      Response errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT || e.type == DioErrorType.RECEIVE_TIMEOUT) {
        errorResponse.statusCode = -2; //NETWORK_TIMEOUT
      }
      print("抛出异常：${e.message}\n");
      print(
          "\n--------------------------------------------请求end--------------------------------------------\n\n");
      return new ResultData(Code.errorHandleFunction(errorResponse.statusCode, e.message), false,
          errorResponse.statusCode, 0);
    }
    print("请求结果：$response\n");
    print(
        "\n--------------------------------------------请求end--------------------------------------------\n\n");
    // 过滤器
    CommonResult result = new CommonResult.fromJson(response.data);
    //1成功,0失败
    if (result.code == 1) {
      return new ResultData(result.data, true, result.code, result.total, message: result.message);
    } else {
      return new ResultData(result.data, false, result.code, result.total, message: result.message);
    }
  }

  ///下载文件
  downloadFile(urlPath, savePath) async {
    Response response;
    try {
      response = await dio.download(urlPath, savePath, onReceiveProgress: (int count, int total) {
        //进度
        print("$count $total");
      });
      print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      print('downloadFile error---------$e');
    }
    return response.data;
  }

  ///取消网络请求
  void cancelRequests(CancelToken token) {
    token.cancel();
  }

  static Future<ResultData> uploadFile(String url, String fileName, String filePath,
      {CancelToken cancelToken}) async {
    print(
        "\n--------------------------------------------请求start--------------------------------------------\n\n");
    print("请求url：${Api.BASE_URL + url}\n");
    print("请求参数：$filePath\n");

//    var formData = FormData.fromMap({
////      "name": "wendux",
//      "filePath": fileName,
//      "file": await MultipartFile.fromFile(filePath),
////      "files": [
////        await MultipartFile.fromFile("./text1.txt", filename: "text1.txt"),
////        await MultipartFile.fromFile("./text2.txt", filename: "text2.txt"),
////      ]
//    });
    Response response;
    try {
      if (null == cancelToken) {
        cancelToken = CancelToken();
      }
      Map<String,String> map = new Map();
      map["Content-Type"] = "multipart/form-data";
      //options: new Options(contentType:"multipart/form-data",headers: map),
//      response = await dio.post(Api.BASE_URL + url, data: formData,
//          cancelToken: cancelToken);
    } on DioError catch (e) {
      Response errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }
      if (e.type == DioErrorType.CONNECT_TIMEOUT || e.type == DioErrorType.RECEIVE_TIMEOUT) {
        errorResponse.statusCode = -2; //NETWORK_TIMEOUT
      }
      print("抛出异常：${e.message}\n");
      print(
          "\n--------------------------------------------请求end--------------------------------------------\n\n");
      return new ResultData(Code.errorHandleFunction(errorResponse.statusCode, e.message), false,
          errorResponse.statusCode, 0);
    }
    print("请求结果：$response\n");
    print(
        "\n--------------------------------------------请求end--------------------------------------------\n\n");
    // 过滤器
    CommonResult result = new CommonResult.fromJson(response.data);
    //1成功,0失败
    if (result.code == 1) {
      return new ResultData(result.data, true, result.code, result.total, message: result.message);
    } else {
      return new ResultData(result.data, false, result.code, result.total, message: result.message);
    }
  }
}

class UrlBuilder {
  var url = "";

  var and = '&';

  UrlBuilder(this.url);

  void get() {
    url += '?';
  }

  void addParam(String k, dynamic v) {
    if (url.endsWith('?')) {
      url += '$k=$v';
    } else {
      url += '&$k=$v';
    }
  }

  String build() {
    return url;
  }
}

class HttpOptionsModel {
  var baseUrl = "";
  var connectTimeout = 5000;
  var receiveTimeout = 5000;
  Map<String, dynamic> headers;

  HttpOptionsModel(this.baseUrl,
      {this.connectTimeout = 5000, this.receiveTimeout = 5000, this.headers});
}
